#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int N = 1e5 + 7;
int n, a[N], b[N], d[N];
int fa[N], sz[N], rk[N];
void init(int n) {
  for (int i = 0; i <= n; ++i) {
    fa[i] = i;
    sz[i] = 1;
    rk[i] = 0;
  }
}
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
void unite(int u, int v) {
  u = find(u), v = find(v);
  if (u == v) return;
  if (rk[u] > rk[v]) {
    fa[v] = u;
    sz[u] += sz[v];
  } else {
    fa[u] = v;
    sz[v] += sz[u];
    if (rk[u] == rk[v]) rk[v]++;
  }
}
int main() {
  int tc;
  cin >> tc;
  while (tc--) {
    cin >> n;
    for (int i = 0; i < n; ++i) cin >> a[i], a[i]--;
    for (int i = 0; i < n; ++i) cin >> b[i], b[i]--;
    for (int i = 0; i < n; ++i) cin >> d[i], d[i]--;

    init(n);

    // 把 a[i] 和 b[i] 两个合并
    for (int i = 0; i < n; ++i) unite(a[i], b[i]);
    unordered_set<int> s;
    // 加入 set
    for (int i = 0; i < n; ++i) s.insert(find(i));
    // 把与 d 有关的去掉
    for (int i = 0; i < n; ++i) {
      if (d[i] == -1) continue;
      s.erase(find(d[i]));
    }
    int pow = 0;
    for (int x : s)
      if (sz[find(x)] > 1) pow++;
    int ans = 1;
    for (int i = 0; i < pow; ++i) {
      ans = (int)((2LL * ans) % mod);
    }
    cout << ans << endl;
  }
}
